package com.kehutong.crm.message.mini;

import java.sql.Timestamp;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.TokenService;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import com.kehutong.crm.message.entity.MessageUser;
import com.kehutong.crm.message.service.MessageService;

/**
 * 小程序端-消息管理
 */
@MvcAction
@ReqMapping("/kht-bin/mini/crm/message")
public class MessageAction {

    private static final Logger logger = LoggerFactory.getLogger(MessageAction.class);

    @Inject
    private MessageService messageService;
    @Inject
    private TokenService tokenService;
    @Inject
    private DoveClient doveClient;

    @ReqMapping("/all/list")
    public Object allList(HttpServletRequest req, JSONObject jsonObject) throws Exception {
        Token token = null;
        try {
            token = tokenService.getUserToken(req);
        } catch (Exception e) {
            return Result.error(0, "系统异常，请稍后重试！");
        }

        if (!checkLogin(token)) {
            return Result.error(0, "请先登录");
        }

        // 若企业编号为空则查询房屋绑定
        String companyNo = ThreadLocalCache.current().getCorpId();
        logger.info("---小程序公司编号改变前：{}--", companyNo);
        if (Objects.isBlank(companyNo)) {
            /*Token userToken = token;
            JSONObject residentHouseBindApplyResult = doveClient.post("/crm/resident/house/bind/service/lastApplyCompanyNo", (http) -> {
                JSONObject userJson = new JSONObject();
                userJson.put("uuid",userToken.getUuid());
                http.setBody(userJson.toJSONString());
            });
            if (residentHouseBindApplyResult != null && residentHouseBindApplyResult.getIntValue("code") == 200) {
                companyNo = residentHouseBindApplyResult.getString("data");
                token.setCompanyNo(companyNo);
                ThreadLocalCache.current().setCorpId(companyNo);
                logger.info("---小程序公司编号改变后：{}--", companyNo);
            }*/
            return Result.success(new ArrayList<>());
        } else {
            return Result.success(messageService.allList(jsonObject, token.getUuid(), companyNo, new Timestamp(token.getUserCreateTime()), true));
        }
    }

    @ReqMapping("/all/noread/count")
    public Object allNoreadCount(HttpServletRequest req, JSONObject jsonObject){
        Token token = null;
        try {
            token = tokenService.getUserToken(req);
        } catch (Exception e) {
            return Result.error(0, "系统异常，请稍后重试！");
        }

        if (!checkLogin(token)) {
            return Result.error(0, "请先登录");
        }

        return Result.success(messageService.allNoreadCount(token.getCompanyNo(), token.getUuid()));
    }

    @ReqMapping("/business/read")
    public Object businessRead(String id){
        messageService.businessRead(id);
        return Result.success();
    }

    @ReqMapping("/bulletin/detail")
    public Object bulletinDetail(String id){
        return messageService.bulletinDetail(id);
    }

    @ReqMapping("/del")
    public Object del(String id){
        return messageService.del(id);
    }

    @ReqMapping("/list")
    public Object list(HttpServletRequest req, JSONObject jsonObject) throws Exception {
        Token token = tokenService.getUserToken(req);

        if (!checkLogin(token)) {
            return Result.error(0, "请先登录");
        }

        return messageService.listMessageUser(jsonObject, token.getUuid(), new Timestamp(token.getUserCreateTime()), true);
    }

    @ReqMapping("/detail")
    public Object detail(MessageUser messageUser) {
        return messageService.detail(messageUser);
    }

    private boolean checkLogin(Token token) {
        if (Objects.isNull(token)) {
            return false;
        }

        if (Objects.isEmpty(token.getUuid()) || token.getUserCreateTime() == 0L) {
            return false;
        } else {
            return true;
        }
    }

}
